//======================
//路由控制器
//======================

//导入API, 操作mysql数据库
let api = require(__basename + '/api/api.js');
let Sequelize = require('sequelize');
let Op = Sequelize.Op;

class RoutesController {
    // 模糊查询
    getUserDo(req, res){
        let rbody = req.body;

        let obj = {
            raw: true,
            where: {
                // name: 'cheny', // 精确查询
                phone: {
                  // 模糊查询
                  [Op.like]:'%' +rbody.phone + '%'
                },
                nickName: {
                  // 模糊查询
                  [Op.like]:'%' +rbody.name + '%'
                },
            },

            attributes: ['id', 'userId','nickName', 'updatedAt', 'phone', 'avatar','address','sex'],
        }
        api.findAll('User', obj).then(result => {
            if (result.length >= 0) {
                res.send({
                    total: result.length,
                    code: '0000',
                    data: result
                })
            }
        }).catch(err => {
            console.log('err=>', err)
        })
    }
    // 查询信息
    getUserList(req, res) {
        let obj = {
            attributes: ['id', 'userId','nickName', 'updatedAt', 'phone', 'avatar','address','sex'],
        }
        api.findAll('User', obj).then(result => {
            if (result.length > 0) {
                res.send({
                    total: result.length,
                    code: '0000',
                    data: result
                })
            }
        }).catch(err => {
            console.log('err=>', err)
        })
    }

    // 查询信息
    getUserInfo(req, res) {
        let rbody = req.body;
        let obj = {
            attributes: ['id', 'userId', 'updatedAt', 'phone', 'avatar'],
            where: {
                id: rbody.id
            }
        }
        api.findAll('User', obj).then(result => {
            console.log(result);
            if (result.length > 0) {
                res.send({
                    total: result.length,
                    code: '0000',
                    data: result[0]
                })
            }
        }).catch(err => {
            console.log('err=>', err)
        })
    }

    // 手机号登录 暂时不做token
    login(req, res) {
        let rbody = req.body;
        let rhead = req.headers;
        console.log(rhead.tk);
        let obj = {
            attributes: ['id', 'userId', 'updatedAt', 'phone', 'avatar'],
            where: {
                phone: rbody.phone,
                password: rbody.password
            }
        }
        api.findAll('User', obj).then(result => {
            console.log(result);
            if (result.length > 0) {
                api.createData('Online', {
                    phone: result[0].phone,
                    userId: result[0].id,
                    token: 'ttokkk'
                }).then(subres => {
                    res.send({
                        code: '0000',
                        msg: '登录成功',
                        data: result[0],
                        token: subres.token
                    })
                })
            } else {
                res.send({
                    code: '',
                    msg: '账号或者密码错误',
                })
            }

        }).catch(err => {
            console.log('err=>', err)
        })
    }

    // 注册,手机号注册
    register(req, res) {
        let rbody = req.body;
        let userId = '_uid' + new Date().getTime();
        console.log(rbody)
        if (!rbody.phone) {
            res.send({
                msg: '请求错误'
            })
        }
        //添加用户数据，注册用户
        api.createData('User', {
            phone: rbody.phone,
            password: rbody.password,
            nickName: `用户:${userId}`,
            userId
        }).then(result => {
            let {
                phone,
                id,
                userId,
                address,
                avatar
            } = result
            res.send({
                msg: '注册成功',
                status: 100,
                result: {
                    phone,
                    id,
                    userId,
                    address,
                    avatar
                }
            });
        }).catch(err => {
            console.log('err ==> ', err);
            res.send({
                msg: '注册失败',
                status: 101
            });
        })
    }

    //注销
    logout(req, res) {
        let rbody = req.body;
        api.delData('Online', {
            where: {
                userId: rbody.id
            }
        }).then(result => {
            res.send({
                code: '0000',
                msg: '注销成功',
                data: result
            })
        })
    }

    // 订单表格控制,按日写入 data:{userId*int,month*int,dateNum*int//日期,consume*str//用电消耗}
    orderLog(req, res) {
        // 订单录入
        let rbody = req.body;
        // 1.先查询id,如表里面有数据,则修改数据,
        let obj = {
            where: {
                userId: rbody.userId,
                month: rbody.month
            }
        }
        api.findAll('Order', obj).then(result => {
            console.log(result);
            if (result.length > 0) {
                let subObj = {};
                subObj[`date_${rbody.dateNum}`] = rbody.consume;
                let where = {
                    where: {
                        id: result[0].id
                    }
                }
                api.update('Order', subObj, where).then(subres => {
                    if (subres > 0) {
                        res.send({
                            code: '00000',
                            msg: '更改成功'
                        })
                    } else {
                        res.send({
                            code: '',
                            msg: '更改失败'
                        })
                    }
                });

            } else {
                // 2.如果没有数据,则创建数据
                let subObj = {
                    userId: rbody.userId,
                    month: rbody.month,
                };
                subObj[`date_${rbody.dateNum}`] = rbody.consume;
                api.createData('Order', subObj).then(subres => {
                    console.log(subres)
                    res.send({
                        code: '00001',
                        msg: '插入成功'
                    })
                })
            }
        }).catch(err => {
            console.log('err=>', err)
        })
    }
    // 根据用户id获取用电情况 data:{userId*int,month}*必传
    orderInfo(req, res) {
        let rbody = req.body;
        let obj = {
            order: [
                ['month', 'ASC']
            ],
            where: {
                userId: rbody.userId,
            }
        }
        if (rbody.month) {
            // 如果传了月份加上月份
            obj.where.month = rbody.month;
        }
        api.findAll('Order', obj).then(result => {
            res.send({
                code: '0000',
                msg: 'success',
                data: result
            })
        })

    }

    // 管理员登录[管理员哪有什么注册]
    manageLogin(req, res){
        let rbody = req.body;
        let rhead = req.headers;
        console.log(rhead.tk);
        let obj = {
            attributes: ['id','userName','phone','email','power'],
            where: {
                phone:rbody.phone,
                password: rbody.password
            }
        }
        api.findAll('Manage', obj).then(result => {
            if (result.length > 0) {
                res.send({
                    code: '0000',
                    msg: 'success',
                    data:result[0]
                })
            } else {
                res.send({
                    code: '',
                    msg: '账号或者密码错误',
                })
            }

        }).catch(err => {
            console.log('err=>', err)
        })
    }

    updateManage(req, res){
        let rbody = req.body;

        // 无id时，创建用户
        if(!rbody.id){
             api.createData('Manage', {
                    phone: rbody.phone,
                    password: '123',
                    userName:rbody.userName,
                    power:rbody.power,
                    email:rbody.email
                }).then(result => {
                    let {
                        phone,
                        userName,
                        email,
                        power
                    } = result
                    res.send({
                        msg: '添加成功',
                        status: 100,
                        result: {
                            phone,
                            userName,
                            email,
                            power
                        }
                    });
                }).catch(err => {
                    console.log('err ==> ', err);
                    res.send({
                        msg: '添加失败',
                        status: 101
                    });
                })   
        }else{
            let obj = {
                where: {
                    id:rbody.id,
                }
            }
            api.findAll('Manage', obj).then(result => {
                if (result.length > 0) {
                    let subObj = {
                        phone: rbody.phone,
                        password: rbody.password,
                        userName:rbody.userName,
                        power:rbody.power,
                        email:rbody.email
                    }
                    let where = {
                        where: {
                            id:rbody.id
                        }
                    }
                    api.update('Manage', subObj, where).then(subres => {
                        if (subres > 0) {
                            res.send({
                                code: '00000',
                                msg: '更改成功'
                            })
                        } else {
                            res.send({
                                code: '',
                                msg: '更改失败'
                            })
                        }
                    });

                } else {
                    res.send({
                        msg:'用户id失效'
                    })   
                }
            }).catch(err => {
                console.log('err=>', err)
            })

        }

    }

    getManageList(req, res){
        let rbody = req.body;
        let obj = {
            where: {
                // name: 'cheny', // 精确查询
                phone: {
                  // 模糊查询
                  [Op.like]:'%' +rbody.phone + '%'
                },
                userName: {
                  // 模糊查询
                  [Op.like]:'%' +rbody.name + '%'
                }
            },
        }
      
        api.findAll('Manage',obj).then(result=>{
            res.send({
                code:'0000',
                msg:'success',
                data:result,
            })
        }).catch(err=>{
            console.log(err);
        })
    }

    delManage(req,res){
        let rbody = req.body;
        api.delData('Manage', {
            where: {
                id: rbody.id
            }
        }).then(result => {
            res.send({
                code: '0000',
                msg: '删除成功',
                data: result
            })
        })
    }

    //获取月用电星系 获取全部，一个用户对应一个表
    // 根据order表格获取所有对应月信息，以及用户信息
    getMonthList(req,res){
        //需要查两个表
       api.findAll('Order').then(result=>{
           let arr = [];
           result.map(item=>{
         
                
                api.findAll('User',{
                    where:{
                        id:item.userId
                    }
                }).then(subResult=>{
                    let arritem = {...item.dataValues};
                    arritem.nickName='';
                    arritem.phone=''
                    arritem.mTotal = 0;
                    for(let i = 1; i < 32; i++){
                        if(item[`date_${i}`]){
                            console.log('=>',item[`date_${i}`])
                            arritem.mTotal += parseInt( item[`date_${i}`] );
                        }
                    }
                    
                    
                    
                    arritem.nickName = subResult[0].nickName;
                    arritem.phone = subResult[0].phone;
                    arr.push(arritem)
                })
                
                
              
            })
            
            setTimeout(function() {
                res.send({
                    data:arr
                })
            }, 1000);
   

        }).catch(err=>{

        })
    }

    //查看latest 
    getLatest(req,res){
        let rbody = req.body;

        let obj = {
            where:{

            }
        }
        if(rbody.userId){
            obj.where.userId = rbody.userId;
        }
        if(rbody.topic){
            obj.where.topic = rbody.topic;
        }

        api.findAll('Latest',obj).then(result=>{
            res.send({
                msg:'success',
                code:'0000',
                data:result
            })
        })
    }

    onPay(req,res){
        let rbody = req.body;     
        
        let whereobj = {
            where: {
                userId:rbody.id,
                month:rbody.month
            }
        }
        let updataObj = {
            pay:rbody.pay
        }

        api.update('Order', updataObj, whereobj).then(subres => {
            if (subres > 0) {
                res.send({
                    code: '00000',
                    msg: '更改成功'
                })
            } else {
                res.send({
                    code: '',
                    msg: '更改失败'
                })
            }
        });

    }

}

//导出实例
module.exports = new RoutesController();